package com.colourclash.fruitopia.views 
{
	import com.colourclash.fruitopia.models.FruitModel;
	import com.colourclash.fruitopia.resources.EmbeddedAssets;
	import com.colourclash.fruitopia.utils.Global;
	import com.greensock.easing.Bounce;
	import com.greensock.easing.SineOut;
	import com.greensock.TweenLite;
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	/**
	 * Displays an item of fruit and handles it's animations
	 * 
	 * @author Patrick Hammond
	 */
	public class FruitView extends Sprite
	{
		
		private var _model:FruitModel;
		public function get model():FruitModel 
		{
			return _model;
		}
		public function set model(value:FruitModel):void 
		{
			_model = value;
		}
		
		private const PIXELS_PER_SECOND:int = 400;
		
		public function FruitView(fruitModel:FruitModel) 
		{
			_model = fruitModel;
			
			name = "fruit" + String(_model.id);
			
			addChild(new EmbeddedAssets[fruitModel.type]() as Bitmap);
			
			x = (52 + _model.column * 90) * Global.getInstance().getScale();
			
			y = -38;
			
			scaleX = scaleY = Global.getInstance().getScale();

			dropDown();
		}
		
		public function updatePosition():void
		{
			swap();
		}
		
		//drop into position with bounce easing
		private function dropDown():void 
		{
			var tweenPosition:Point = getTweenToPosition();

			if (tweenPosition)
				TweenLite.to(this, (tweenPosition.y - y) / PIXELS_PER_SECOND, {x:tweenPosition.x, y:tweenPosition.y, ease:Bounce.easeOut, onComplete:tweenComplete} );
		}
		
		//slide into position
		private function swap():void 
		{
			var tweenPosition:Point = getTweenToPosition();

			if (tweenPosition)
				TweenLite.to(this, .3, {x:tweenPosition.x, y:tweenPosition.y, ease:SineOut.ease, onComplete:tweenComplete} );
		}

		//animation done, inform the main view
		private function tweenComplete():void 
		{
			dispatchEvent(new Event(Event.COMPLETE, true));
		}
		
		//the screen position we should move to
		private function getTweenToPosition():Point 
		{
			var targetYPosition:int = (155 + _model.row * 90) * Global.getInstance().getScale();
			var targetXPosition:int = (52 + _model.column * 90) * Global.getInstance().getScale();
			
			if (int(targetXPosition) == int(x) && int(targetYPosition) == int(y))
				return null;
			
			return new Point(targetXPosition, targetYPosition);
		}
		
	}

}